<template>
  <div class="chart-item">
    <p
      v-if="isShowTitle"
      :style="{cursor: (reportId && reportName) ? 'pointer' : 'default', ...getTitleStyle()}"
      :title="(reportId && reportName) ? reportName : ''"
      class="item-header"
      @click="goDetail(reportId, reportName)">{{ moduleItemData.name }}<tipIcon v-if="RemarkOptions.showRemark && RemarkOptions.value" :content="RemarkOptions.value" class="ml4"/></p>
    <div :ref="`dom-${chartID}`">
      <ve-chart
        v-if="!isEmpty"
        :ref="chartID"
        :data="chartData"
        :theme="chartsTheme"
        :settings="chartSettings"
        :extend="handelOptins(extendOptions)"
        :data-zoom="dataZoom"
        :loading="loading"
        :data-empty="isEmpty"
        :height="isShowTitle ? `${showAreaMaxHeight - getTitleFontSize() - 20}px` : `${showAreaMaxHeight}px`"
        :events="chartEvents"
        resizeable/>
      <div v-else class="empty-container">
        <img :src="emptyIcon" alt="">
        <div class="label">暂无数据</div>
      </div>
    </div>
    <span v-if="isNeedAxis_X && axisConfig_X.AxisName && !isEmpty" class="x-axis-name">{{ axisConfig_X.AxisName }}</span>
    <span v-if="isNeedAxis_Y && axisConfig_Y.AxisName && !isEmpty" class="y-axis-name">{{ axisConfig_Y.AxisName }}</span>
    <el-button-group v-if="canEdit && !isPreview" :class="changeBtnGroupClass" class="fr i999">
      <el-button size="mini" icon="el-icon-arrow-left" @click="changeType(0)"/>
      <el-button size="mini" icon="el-icon-arrow-right" @click="changeType(1)"/>
    </el-button-group>
  </div>
</template>

<script>
import 'v-charts/lib/line.common'; // 折线图、面积图
import 'v-charts/lib/bar.common'; // 条形图
import 'v-charts/lib/histogram.common'; // 柱状图
import 'v-charts/lib/pie.common'; // 饼图
import 'v-charts/lib/ring.common'; // 环图
import 'v-charts/lib/funnel.common'; // 漏斗图
import 'v-charts/lib/radar.common'; // 雷达图
// import 'v-charts/lib/waterfall.common'; // 瀑布图

import 'echarts/lib/component/dataZoom'; // 对应功能包
import 'echarts/lib/component/legendScroll.js';
// import 'echarts/lib/component/tooltip';
// import 'echarts/lib/component/title';
// import 'echarts/lib/component/toolbox';
// import 'echarts/lib/component/axis';
// import 'echarts/lib/component/legend';

import VeChart from 'v-charts/lib/chart.common'; // 综合图，用于切换图类型，通过setting > type
import echarts from 'echarts';
import 'v-charts/lib/style.css';
import { isNumber } from '@/utils/tools';
import { chartTypeList, chartColorList } from '@/filters/status';
import { moneyFilter, numberTextFormat } from '@/filters/number';
import emptyIcon from '@/assets/empty-table-data.png';
import { mapState } from 'vuex';
export default {
  name: 'ChartItem',
  components: { VeChart },
  props: {
    columnsDataType: { // 见rows注释
      type: Boolean,
      default: true
    },
    indexKeyMode: { // columnsDataType为true时：true-使用角标作为列Key，false-为以columns名为列Key
      type: Boolean,
      default: true
    },
    isDataZoom: { // 是否缩放
      type: Boolean,
      default: false
    },
    canEdit: {
      type: Boolean,
      default: true
    },
    showAreaMaxHeight: {
      type: Number,
      default: 100
    },
    changeBtnGroupClass: {
      type: String,
      default: ''
    },
    theme: {
      type: [String, Boolean],
      default: 'highlight' // dark
    },
    refID: {
      type: [String, Number],
      default: ''
    },
    tagForResize: {
      type: Boolean,
      default: false
    },
    loading: {
      type: Boolean,
      default: false
    },
    // 全局的样式，修改标题边距
    chartConfig: {
      type: Object,
      default: () => ({})
    },
    columns: {
      type: Array,
      default: () => []
      // default: () => ['日期', '访问用户', '下单用户', '下单率']
    },
    rows: {
      type: Array,
      default: () => []
      // columnsDataType true时传入格式
      // default: () => [['1/1', 1393, 5000, 50], ['1/2', 500, 4000, 32]]
      // columnsDataType false时传入格式
      // default: () => [
      //   {
      //     '日期': '1/1',
      //     '访问用户': 1393,
      //     '下单用户': 1093,
      //     '下单率': 0.32
      //   }, {
      //     '日期': '1/2',
      //     '访问用户': 3530,
      //     '下单用户': 3230,
      //     '下单率': 0.26
      //   }]
    },
    isPreview: { // 预览模式，预览模式下隐藏部分功能
      type: Boolean,
      default: false
    },
    moduleItemData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    this.typeArr = chartTypeList.map(i => i.type); // waterfall插件存在bug，columns的一二列必须对应为xy，且y为数值
    this.chartEvents = {
      click: (e) => {
        console.log(e);
      }
    };
    return {
      emptyIcon,
      chartsTheme: {},
      curTypeIndex: this.getRealChartType(this.chartType).index,
      chartData: {
        columns: [],
        rows: []
      },
      pieColorList: [],
      chartSettings: {
        type: this.getRealChartType(this.chartType).type,

        // metrics: ['2', '1'], // 指标维度Y, 默认除第一列外所有列
        // dimension: ['0'], // 指标维度X，默认第一列
        // waterfall图表格式
        // dimension: 0,
        // metrics: 1

        // 双y轴 堆叠面积图不需要双轴 组合条形图双轴在top
        axisSite: (this.yAxisCombo && this.chartType !== 12) ? (this.chartType === 11 ? { top: [this.yAxisCombo] } : { right: [this.yAxisCombo] }) : {},
        // yAxisType: ['KMB', 'percent'],
        // yAxisType: ['0,0a']
        // yAxisName: ['数值', '比率']

        // 堆叠
        // stack: { '用户': ['访问用户', '下单用户'] },
        // 面积
        // area: true
        // 别名
        // labelMap: {}
        // labelMap: {
        //   'PV': '访问用户',
        //   'Order': '下单用户'
        // },
        // legendName: {
        //   '访问用户': '访问用户 total: 10000'
        // }
        // 设置横轴为连续的数值轴
        // xAxisType: 'value'
        // 设置横轴为连续的时间轴
        // xAxisType: 'time'

        // 柱状图 指定折线列
        showLine: this.yAxisCombo ? [this.yAxisCombo] : [],

        // 饼状图： 玫瑰图
        // roseType: 'radius'
        // 限制显示条数饼图
        // limitShowNum: 5
        // 多圆饼图
        // level: [
        //   ['1/1', '1/2', '1/3'],
        //   ['1/4', '1/5']
        // ]
        // 设置数据类型
        // dataType: 'percent'
        // dataType: {
        //   '访问用户': 'KMB',
        //   '年龄': 'percent',
        //   '下单用户': 'normal'
        // }
        // dataType: function (v) {
        //   return v + ' ￥'
        // }
        // 设置饼图半径边距
        // radius: 10,
        // offsetY: 300

        // 瀑布图设置 总计、剩余 的名称
        // totalNum: 24,
        // totalName: '总时间',
        // remainName: '剩余时间'

        // 漏斗图
        // 自动按照数值排序
        useDefaultOrder: true,
        // 过滤0值
        filterZero: true
        // 定制顺序漏斗图
        // sequence: ['订单', '点击', '访问', '展示']
        // 金字塔
        // ascending: true
      }
    };
  },
  computed: {
    ...mapState({
      'colorList': state => state.options.colorList
    }),
    xAxis() {
      return this.moduleItemData.xAxis || '0';
    },
    yAxis() {
      return this.moduleItemData.yAxis || [];
    },
    yAxisCombo() {
      return this.moduleItemData.yAxisCombo || '';
    },
    chartType() {
      return this.moduleItemData.type || 'line';
    },
    contrastData() {
      // 获取对比数据，只有当图型为折线对比图时生效
      return this.moduleItemData.tableData;
    },
    contrastTimeArr() { // 只有当图型为折线对比图时生效
      return this.moduleItemData.contrastTimeArr;
    },
    styleConfig() {
      return this.moduleItemData.styleConfig;
    },
    allColorList() {
      return [...chartColorList, ...this.colorList];
    },
    isDataLabel() {
      return this.moduleItemData.isDataLabel;
    },
    isShowTitle() {
      return this.moduleItemData.name && (this.getTitleStyle() && !this.getTitleStyle().isHide);
    },
    RemarkOptions() {
      return (this.getTitleStyle() && this.getTitleStyle().RemarkOptions) || {};
    },
    minData() {
      let minData = 0;
      if (this.chartType === 9) {
        this.chartData.rows.forEach(i => {
          for (let index = 1; index < i.length; index++) {
            if (isNumber(i[index]) && i[index] < minData) minData = i[index];
          }
        });
      }
      return minData;
    },
    chartID() {
      return `ve-chart-${this.refID}`;
    },
    isEmpty() {
      return this.chartData.columns.length === 0 || this.chartData.rows.length === 0;
    },
    isIndexKeyMode() {
      return this.columnsDataType && this.indexKeyMode;
    },
    isVerticallegend() {
      return ['pie', 'ring', 'radar'].indexOf(this.chartSettings.type) >= 0;
    },
    isSingleMetrics() {
      return ['pie', 'ring', 'funnel', 'waterfall'].indexOf(this.chartSettings.type) >= 0;
    },
    isXYAxisType() {
      return ['radar', 'pie', 'ring', 'funnel'].indexOf(this.chartSettings.type) < 0;
    },
    isOfsetY() {
      return ['pie', 'ring'].indexOf(this.chartSettings.type) >= 0;
    },
    isPercentLabel() {
      return ['pie', 'ring', 'funnel'].indexOf(this.chartSettings.type) >= 0;
    },
    isNeedAxis_X() {
      return this.moduleItemData.showXAxis && this.isXYAxisType;
    },
    isNeedAxis_Y() {
      return this.moduleItemData.showYAxis && this.isXYAxisType;
    },
    axisConfig_X() {
      return this.styleConfig && this.styleConfig.axisConfig_X ? this.styleConfig.axisConfig_X : {};
    },
    axisConfig_Y() {
      return this.styleConfig && this.styleConfig.axisConfig_Y ? this.styleConfig.axisConfig_Y : {};
    },
    isNeedGrid() {
      return this.moduleItemData.isGrid && this.isXYAxisType;
    },
    isLegend() {
      return this.moduleItemData.isLegend;
    },
    reportId() {
      return this.moduleItemData.reportId || '';
    },
    reportName() {
      return this.moduleItemData.reportName || '';
    },
    dataZoom() {
      const inside = {
        type: 'inside',
        start: 0,
        end: 100
      };
      const slider = {
        type: 'slider',
        start: 0,
        end: 30
      };
      // 有xy 开启缩放轴或者数量超过30内部缩放
      return this.isXYAxisType && this.isDataZoom ? [slider] : this.isXYAxisType && this.rows && this.rows.length > 30 ? [inside] : undefined;
    },
    extendOptions() { // 属性也可以是这种形式'xAxis.0.axisLabel.rotate': 45 // 折线图：横坐标的倾斜
      // const tooltip = this.isSingleMetrics ? {
      //   // trigger: this.isSingleMetrics ? 'axis' : 'item',
      //   trigger: 'item',
      //   formatter: function(params) {
      //     var res = params.name + '<br/>' + Object.keys(params.value).map(key => {
      //       return params.value[params.encode.y[0]];
      //     })
      //     return res;
      //   }
      // } : {};
      // 提示框取默认值，即鼠标移动到柱状图会显示内容,
      // v-charts设置数据格式，折线图使用 yAxisType, 饼图使用 dataType，支持numerify设置数字格式，但同时影响y轴格式
      let tooltip = {
        axisPointer: {
          type: 'line',
          lineStyle: {
            color: '#bbbbbb5c',
            type: 'dashed'
          }
        }
      };
      const contrastTimeArr = this.contrastTimeArr;
      if (this.chartType === 13 && this.contrastTimeArr && this.contrastTimeArr.items && this.contrastTimeArr.items.length) {
        tooltip = {
          formatter(datas) { // 自定义获取，需要根据图表类型获取对应值，不同图表，值结构不同
          // debugger;
            let res = '';
            let val;
            for (let i = 0; i < datas.length; i++) {
              val = datas[i].value[1];
              const seriesName = datas[i].seriesName;
              let contrastTime = '';
              if (contrastTimeArr.YAxis.includes(seriesName)) {
                // const contrastText = contrastTimeArr.contrastText;
                contrastTimeArr.items.forEach(j => {
                  if (j.time === datas[i].name) {
                    contrastTime = j.contrastTime;
                  }
                });
                // if (contrastTime !== '' && contrastText) seriesName = seriesName.replace(contrastText, '');
                // seriesName = seriesName + `${contrastTime ? '(' + contrastTime + ')' : ''}`;
              }
              const htmlStr = `
                <div>
                  <div>${contrastTime}</div>
                  <div style="display:flex;align-items:center;">
                    ${(val || val === 0) ? `
                    <div>${seriesName}：</div>
                    <div>${moneyFilter(val)}</div>` : ''}
                  </div>
                </div>
              `;
              res += htmlStr;
            }
            const reshHtml = `
              <div>
                <div>${datas[0].name}</div>
                ${res}
              </div>
            `;
            return reshHtml;
          }
        };
      }
      const legend = this.isVerticallegend ? { // 标签位置
        type: 'scroll',
        orient: 'vertical',
        right: 0,
        top: 0,
        bottom: 20,
        show: this.isLegend // 图例项
      } : {
        type: 'scroll',
        right: 0,
        padding: [0, 0, 10, 0],
        show: this.isLegend // 图例项
      };
      const series = this.isPercentLabel ? { // 饼图线文字
        // type: chartTypeList[this.curTypeIndex].eType, // 必须设置，否则导致series.type必须、.seriesTaskMap of null等错误
        label: { // 数据标签
          show: this.isDataLabel,
          // formatter: '{d}%'
          formatter: this.isLabelWithLegend ? '{b}{d}%' : '{d}%'
        }
      } : {
        // type: this.yAxisCombo ? 'custom' : chartTypeList[this.curTypeIndex].eType,
        // barWidth: '30%', // 多柱状条会导致重叠
        barMaxWidth: 23,
        label: { // 数据标签， 2020-06-10 新增
          show: this.isDataLabel,
          position: chartTypeList[this.curTypeIndex].type === 'bar' ? 'right' : 'top', // 条形图的标签在右边
          formatter: (params) => { // 格式化数据的函数
            if (!isNumber(params.data)) {
              if (params.data instanceof Array && params.data.length === 2 && isNumber(params.data[1])) {
                return [moneyFilter(numberTextFormat(params.data[1], 1), false)]; // params.data[0],
              }
              return params.data || '';
            } else {
              if (params.data >= 0) {
                return moneyFilter(numberTextFormat(params.data, 1), false);
              } else {
                return '-' + moneyFilter(numberTextFormat(Math.abs(params.data), 1), false);
              }
            }
          }
        }
      };
      // 设置颜色
      let color = this.findColors(this.moduleItemData.chartColor);
      const isGradient = this.moduleItemData.isGradient;
      if (isGradient) {
        if (this.chartType === 3 || this.chartType === 6) {
        // 饼图或环形图
          color = this.pieColorList;
        } else {
          color = this.getColorList(color, this.chartType);
        }
      }

      const isNeedGrid = this.isNeedGrid;

      const axisConfig_X = this.axisConfig_X;
      const axisConfig_Y = this.axisConfig_Y;
      const isNeedAxis_Y = this.isNeedAxis_Y;
      const minData = this.minData;
      // let backgroundColor;
      if (this.chartType === 3) {
        series.radius = '70%';
        series.center = ['50%', '50%'];
      } else if (this.chartType === 6) {
        series.radius = ['40%', '55%'];
        series.center = ['50%', '50%'];
        series.labelLine = { normal: { length: 1 }};
      }
      // 折线平滑度： 0 ～ 1
      const smooth = this.styleConfig && this.styleConfig.lineSmooth ? this.styleConfig.lineSmooth.smooth : undefined;
      // 柱状图圆角值
      const borderRadius = this.styleConfig && this.styleConfig.barRadius ? this.styleConfig.barRadius.borderRadius : undefined;
      if (smooth) {
        series.smooth = smooth;
      }
      if (borderRadius) {
        if (!series.itemStyle) series.itemStyle = {};
        series.itemStyle.barBorderRadius = borderRadius;
      }
      // this.styleConfig.map(item => {
      //   if (item.title === '背景配置：') {
      //     item.config.forEach(val => {
      //       if (val.word === 'backgroundColor') {
      //         backgroundColor = val.value;
      //       }
      //     });
      //   }
      // });
      let gridTop = !this.isLegend ? 10 : 30;
      if (this.isDataLabel) gridTop = gridTop + 15;
      return {
        color,
        legend,
        series,
        backgroundColor: 'transparent', // 设置图表背景图
        tooltip,
        grid: {
          // show: true,
          // right: this.isVerticallegend ? 1000 : 0,
          top: gridTop, // 图表左边距
          left: '2%', // 图表左边距
          right: '2%',
          bottom: this.isDataZoom ? 45 : this.isXYAxisType ? '2%' : undefined,
          // borderColor: 'transparent'
          // backgroundColor: 'transparent'
          containLabel: true
        },
        // toolbox: {
        //   feature: {
        //     saveAsImage: {}
        //   }
        // },
        xAxis: {
          position: axisConfig_X.Position || 'bottom',
          splitLine: { // 去除网格线
            show: false
            // show: this.isNeedGrid
          },
          // splitArea: { // 保留网格区域
          //   show: true
          // },
          axisLabel: {
            show: this.isNeedAxis_X,
            color: axisConfig_X.color || '#606266',
            fontSize: axisConfig_X.fontSize || 12,
            inside: false,
            rotate: axisConfig_X.rotate === -90 ? 0 : (axisConfig_X.rotate || 0),
            splitLine: { // 去除网格线
              show: false
            },
            formatter: (params) => {
              // if (this.chartType !== 4) return params;
              let label = null;
              if (typeof params !== 'number') {
                label = params || '';
              } else {
                label = moneyFilter(numberTextFormat(params, 1), false);
              }
              return axisConfig_X.rotate === -90 ? String(label).split('').join('\n') : label;// X轴纵向显示
            }
            // textStyle: {
            //   color: '#fff'
            // }
          },
          axisTick: {
            show: false
          },
          axisLine: {
            show: false
          }
          // z: 10
        },
        // yAxis: y,
        yAxis: function(item) {
          if (!item) {
            return {
              position: axisConfig_Y.Position || 'left',
              splitLine: { show: isNeedGrid, lineStyle: { type: 'dotted' }},
              axisLine: { show: false },
              axisTick: { show: false },
              axisLabel: {
                color: axisConfig_Y.color || '#606266',
                fontSize: axisConfig_Y.fontSize || 12,
                rotate: axisConfig_Y.rotate || 0,
                show: isNeedAxis_Y, splitLine: { show: false }, // 去除网格线
                formatter: (params) => {
                  if (!isNumber(params)) {
                    return params || '';
                  } else {
                    if (params >= 0) {
                      return moneyFilter(numberTextFormat(params, 1), false);
                    } else {
                      return '-' + moneyFilter(numberTextFormat(Math.abs(params), 1), false);
                    }
                  }
                }
              }
            };
          }
          item.forEach(i => {
            i.position = axisConfig_Y.Position || 'left';
            i.show = true;
            i.splitLine = { show: isNeedGrid, lineStyle: { type: 'dotted' }}; // 去除网格线
            i.axisLine = { show: false };
            i.axisTick = { show: false };
            i.axisLabel = {
              color: axisConfig_Y.color || '#606266',
              fontSize: axisConfig_Y.fontSize || 12,
              rotate: axisConfig_Y.rotate || 0,
              show: isNeedAxis_Y, splitLine: { show: false }, // 去除网格线
              formatter: (params) => {
                if (!isNumber(params)) {
                  return params || '';
                } else {
                  if (params >= 0) {
                    return moneyFilter(numberTextFormat(params, 1), false);
                  } else {
                    return '-' + moneyFilter(numberTextFormat(Math.abs(params), 1), false);
                  }
                }
              }
            };
            if (item.length === 2 && minData < 0) {
              i.min = function(value) {
                if (Math.abs(value.max) > Math.abs(value.min)) {
                  return (-Math.abs(value.max) * 0.4).toFixed(1);
                } else {
                  return (-Math.abs(value.min) * 0.4).toFixed(1);
                }
              };
            }
          });
          if (item.length === 2 && item[0].position === item[1].position) {
            item[1].position = item[0].position === 'left' ? 'right' : 'left';
          }
          return item;
        }
      };
    },
    isLabelWithLegend() {
      return this.moduleItemData.isLabelWithLegend;
    }
  },
  watch: {
    theme: {
      handler(newVal, oldVal) {
        this.setTheme();
      },
      immediate: false
    },
    xAxis: {
      handler(newVal, oldVal) {
        this.changeDimension();
      },
      immediate: false
    },
    yAxis: {
      handler(newVal, oldVal) {
        this.changeMetrics();
      },
      immediate: false
    },
    tagForResize: {
      handler(newVal, oldVal) {
        this.changeSize();
        this.setPieColor();
      },
      immediate: false
    },
    chartType: {
      handler(newVal, oldVal) {
        this.setRealChartType(newVal);
      },
      immediate: false
    },
    columns: {
      handler(newVal, oldVal) {
        this.setChartColumns(newVal); // 有先后
        this.setChartRows(this.rows); // 有先后
        this.changeDimension();
        this.changeMetrics();
        this.changeSize();
      },
      immediate: false
    },
    rows: {
      handler(newVal, oldVal) {
        this.setChartRows(newVal); // 有先后
        this.setChartColumns(this.columns); // 有先后
        this.changeDimension();
        this.changeMetrics();
        this.changeSize();
      },
      immediate: false
    }
  },
  mounted() {
    this.getColor();
    this.setTheme();
    this.setRealChartType(this.chartType);
    this.dataChange();
    this.changeSize();
    this.setPieColor();
  },
  methods: {
    // 打开报表
    goDetail(reportId, reportName) {
      if (!reportId || !reportName) return;
      this.$router.push({
        name: 'totalTabelData',
        params: { fileId: reportId },
        query: { name: encodeURIComponent(reportName), categoryName: '', reportType: '' }
      });
    },
    setTheme() {
      switch (this.theme) {
        case true:
        case 'highlight':
          this.chartsTheme = require('@/assets/chartsTheme/crm-highlight-theme.json');
          break;
        case false:
        case 'dark':
          this.chartsTheme = require('@/assets/chartsTheme/crm-dark-theme.json');
          break;
        default:
          this.chartsTheme = require('@/assets/chartsTheme/crm-highlight-theme.json');
          break;
      }
    },
    dataChange() {
      this.setChartRows(this.rows); // 有先后
      this.setChartColumns(this.columns); // 有先后
      this.changeDimension();
      this.changeMetrics();
      this.changeSize();
    },
    changeDimension() {
      let dimension = 0;
      if (this.isIndexKeyMode) { // 传入行name为key 或者 传入行index为key且展示以index为key
        dimension = this.columns.indexOf(this.xAxis) + '';
        if (dimension < 0) dimension = '0';
      } else {
        dimension = this.xAxis;
      }
      if (this.isSingleMetrics) { // 找到第一个值为数字的作为y
        this.chartSettings.dimension = dimension;
      } else {
        this.chartSettings.dimension = [dimension];
      }
    },
    changeMetrics() {
      let metrics = [];
      if (!this.columnsDataType || this.isIndexKeyMode) { // 传入行name为key 或者 传入行index为key且展示以index为key
        if (this.columns && this.columns.length > 0) metrics = this.yAxis.map(i => this.columns.indexOf(i) + '').filter(i => i !== '-1');
        if (metrics.length === 0) metrics = undefined;
      } else {
        metrics = this.yAxis;
      }
      if (metrics) {
        if (this.isSingleMetrics) { // 找到第一个值为数字的作为y
          this.chartSettings.metrics = this.rows && this.rows.length > 0 ? (metrics[metrics.findIndex(i => isNumber(this.rows[0][i]))] || metrics[0]) : (metrics[0]);
        } else {
          this.chartSettings.metrics = metrics;
        }
      }
    },
    getNextTypeIndex(isNext, curIndex) {
      isNext ? curIndex++ : curIndex--;
      if (curIndex >= this.typeArr.length) curIndex = 0;
      else if (curIndex < 0) curIndex = this.typeArr.length - 1;
      return curIndex;
    },
    changeType(isNext, curIndex = this.curTypeIndex) {
      curIndex = this.getNextTypeIndex(isNext, curIndex);
      if (chartTypeList[curIndex].hide) {
        this.changeType(isNext, curIndex);
      } else if (Boolean(this.yAxisCombo) !== Boolean(chartTypeList[curIndex].isCombo)) { // 组合不匹配
        this.changeType(isNext, curIndex);
      } else {
        this.setRealChartType(curIndex);
      }
    },
    getRealChartType(type) { // 查询图表类型
      let info;
      if (typeof type === 'string' && isNaN(Number(type))) {
        info = { type, index: this.typeArr.indexOf(type) };
      } else {
        info = { type: this.typeArr[Number(type)], index: type };
      }
      if (info.type === 'line-area') info.type = 'line'; // 面积图实际为折线图
      return info;
    },
    setRealChartType(type) { // 设置图表类型
      const realChartType = this.getRealChartType(type);
      this.chartSettings.type = realChartType.type;
      this.curTypeIndex = realChartType.index;

      // 相关适配
      this.changeDimension();
      this.changeMetrics();

      const offsetY = this.isOfsetY ? 150 : 0; // 饼图环形图顶部适配
      if (this.chartSettings.offsetY !== offsetY) this.chartSettings.offsetY = offsetY;

      const isLineArea = this.curTypeIndex === 5 || this.curTypeIndex === 12;
      this.chartSettings.area = isLineArea; // 面积图实际为折线图
      if (isLineArea) this.chartSettings.stack = { '总量': this.chartSettings.metrics }; // 面积图实际为折线图
      else this.chartSettings.stack = {};
    },
    setChartRows(tempRows) {
      if (!this.columnsDataType || this.isIndexKeyMode) { // 传入行name为key 或者 传入行index为key且展示以index为key
        this.chartData.rows = tempRows;
      } else {
        // const columns = this.chartData.columns;
        const columns = this.columns;
        if (!columns || columns.length === 0) return;
        const rows = [];
        tempRows.forEach((itemRow, indexRow) => {
          const obj = {};
          columns.forEach((itemCol, indexCol) => {
            obj[itemCol] = itemRow[indexCol];
          });
          rows.push(obj);
        });
        this.chartData.rows = rows;
      }
      // 把对比的数据加入到原数据
      if (this.contrastData && this.contrastData.rows && this.chartType === 13) {
        const contrastDataRows = JSON.parse(JSON.stringify(this.contrastData.rows));
        let dimension = 0;
        if (this.chartSettings && this.chartSettings.dimension) {
          dimension = typeof this.chartSettings.dimension === 'object' ? Number(this.chartSettings.dimension[0]) : Number(this.chartSettings.dimension);
        }
        const chartDataRows = [];
        this.chartData.rows.forEach(i => {
          contrastDataRows.forEach(j => {
            if (i.length > dimension && i[dimension] === j[dimension]) {
              j.splice(dimension, 1);
              chartDataRows.push(i.concat(j));
            }
          });
        });
        this.chartData.rows = chartDataRows;
      }
      // 把对比的数据加入到原数据 end
    },
    setChartColumns(tempColumns) {
      if (this.isIndexKeyMode) {
        const columns = [];
        const labelMap = {};
        // 把对比的数据加入到原数据
        if (this.contrastData && this.contrastData.columns && this.chartType === 13) {
          const contrastDataColumns = JSON.parse(JSON.stringify(this.contrastData.columns));
          let dimension = 0;
          if (this.chartSettings && this.chartSettings.dimension) {
            dimension = typeof this.chartSettings.dimension === 'object' ? Number(this.chartSettings.dimension[0]) : Number(this.chartSettings.dimension);
          }
          const contrastText = (this.contrastTimeArr) ? this.contrastTimeArr.contrastText || '对比' : '对比';
          contrastDataColumns.splice(dimension, 1);
          for (let i = 0; i < contrastDataColumns.length; i++) {
            contrastDataColumns[i] = `${contrastText}${contrastDataColumns[i]}`;
          }
          tempColumns = tempColumns.concat(contrastDataColumns);
        }
        // 把对比的数据加入到原数据 end
        tempColumns.forEach((item, index) => {
          // 组合图形字段对应
          if (this.yAxisCombo === item) {
            this.chartSettings.showLine = [(index).toString()];
            if (this.chartType !== 12) {
              this.chartSettings.axisSite = this.chartType === 11 ? { top: [(index).toString()] } : { right: [(index).toString()] };
            }
          }
          labelMap[`${index}`] = item;
          columns.push(`${index}`);
        });
        this.chartData.columns = columns;
        this.chartSettings.labelMap = labelMap;
      } else {
        if (!this.columnsDataType && (!tempColumns || tempColumns.length === 0) && this.chartData.rows && this.chartData.rows.length > 0) tempColumns = Object.keys(this.chartData.rows[0]);
        this.chartData.columns = tempColumns;
      }
    },
    changeSize() {
      this.$nextTick(() => {
        this.$refs[this.chartID] && this.$refs[this.chartID].echarts && this.$refs[this.chartID].echarts.resize();
      });
    },
    /**
     * 自定义样式
     */
    getTitleStyle() {
      const styleConfig = this.styleConfig;
      let styleObj = {};
      if (styleConfig && styleConfig instanceof Array) {
        // 兼容旧数据
        return this.moduleTitleSy();
      } else if (styleConfig && styleConfig instanceof Object) {
        styleObj = { ...styleConfig.moduleName };
        // styleObj.lineHeight = styleObj.fontSize = styleObj.fontSize + 'px'; // 避免字体造成高度计算错误
        styleObj.marginBottom = this.chartConfig.modulePadding ? this.chartConfig.modulePadding + 'px' : '12px';
        if (styleObj.FontStyle && styleObj.FontStyle instanceof Array) {
          if (styleObj.FontStyle.includes('italic')) styleObj.fontStyle = 'italic';
          if (!styleObj.FontStyle.includes('bolder')) styleObj.fontWeight = 'normal';
        }
        return styleObj;
      } else {
        return {};
      }
    },
    getTitleFontSize() {
      const styleConfig = this.styleConfig;
      if (styleConfig && styleConfig instanceof Array) {
        // 兼容旧数据
        return 32;
      } else if (styleConfig && styleConfig instanceof Object && styleConfig.moduleName) {
        return styleConfig.moduleName.fontSize;
      } else {
        return 0;
      }
    },
    moduleTitleSy() {
      const moduleTitleStyle = {};
      this.styleConfig.map(item => {
        if (item.title === '模块名称：') {
          item.config.forEach(val => {
            if (val.word === 'fontSize' && val.unit) {
              if (val.value.toString().indexOf('px') === -1) {
                val.value = `${val.value}${val.unit}`;
              }
            }
            moduleTitleStyle[val.word] = val.value;
          });
        }
      });
      return moduleTitleStyle;
    },
    handelOptins(options) {
      let extendEchartsOptions = null;
      if (this.styleConfig && this.styleConfig.echartsConfig && this.styleConfig.echartsConfig.value) {
        let value = this.styleConfig.echartsConfig.value;
        try {
          value = value.replace(/(\w+):/gis, '"$1":');
          value = value.replace(/'/g, '"');
          extendEchartsOptions = JSON.parse(value);
        } catch (error) {
          extendEchartsOptions = null;
        }
      }
      if (extendEchartsOptions) {
        Object.assign(options, extendEchartsOptions);
      }
      return options;
    },
    getColorList(colorList, chartType) {
      if (!colorList) return '';
      const n = colorList.length;
      const ans = new Array(n);
      for (let i = 0; i < n; i++) {
        const end = i === n - 1 ? 0 : i + 1;
        ans[i] = this.getGradientColor(colorList[i], colorList[end], chartType);
      }
      return ans;
    },
    setPieColor() {
      const isGradient = this.moduleItemData.isGradient;
      if (!isGradient) return;
      this.$nextTick(() => {
        const chartType = this.chartType;
        const colorList = this.findColors(this.moduleItemData.chartColor);
        const n = colorList.length;
        const ans = new Array(n);
        for (let i = 0; i < n; i++) {
          const end = i === n - 1 ? 0 : i + 1;
          ans[i] = this.getGradientColor(colorList[i], colorList[end], chartType);
        }
        this.pieColorList = ans;
      });
    },
    getGradientColor(start, end, chartType) {
      if (chartType === 3 || chartType === 6) {
        /**
         * 径向渐变
         * 前三个参数分别是圆心x, y 和半径，取值同线性渐变, offset的范围是0 ~ 1, 用于表示位置
         */
        const width = this.$refs[`dom-${this.chartID}`].clientWidth;
        const height = this.$refs[`dom-${this.chartID}`].clientHeight;
        const r = Math.min(width / 2, height / 2);
        const color = new echarts.graphic.RadialGradient(width / 2, height / 2, r, [
          { offset: 1, color: start },
          { offset: 0, color: end }
        ]);
        color.global = true;
        return color;
      } else {
      /**
       * 线性渐变
       * 四个数字分别代表：右、下、左、上
       * offset的范围是0 ~ 1, 用于表示位置
       */
      // 条形图时从左往右，其他类型都是从下往上
        const ans = chartType === 4 || chartType === 11 ? [0, 0, 1, 0] : [0, 1, 0, 0];
        return new echarts.graphic.LinearGradient(...ans, [
          { offset: 0, color: start },
          { offset: 1, color: end }
        ]);
      }
    },
    getColor() {
      if (this.colorList.length === 0) {
        this.$store.dispatch('GetColorList');
      }
    },
    findColors(label) {
      if (!label) return '';
      const item = this.allColorList.find(i => {
        return i.label === label;
      });
      const ans = item ? item.colors : this.allColorList[0].colors;
      return [...ans, ...ans];
    }
  }
};
</script>

<style lang="scss" scoped>
.chart-item {
  position: relative;
  width: 100%;
  .item-header {
    font-weight: bolder;
    font-size:20px;
    color:rgba(51,51,51,1);
    // padding: 0 8px;
    margin: 0 0 12px;
    line-height: 1.2;
    /*line-height: 23px;*/
    /*height: 24px;*/
    // border-left: 4px solid rgba(64,110,255,1);
  }
}
.empty-container{
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  overflow: hidden;
  margin-top: 20px;
  img {
    width: 120px;
  }
  .label {
    font-size: 14px;
    color: #999999;
    margin-top: 10px;
  }
}
.x-axis-name {
  position: absolute;
  right: 0px;
  bottom: -8px;
  font-size: 16px;
}
.y-axis-name {
  position: absolute;
  top: 32px;
  left: 0px;
  font-size: 16px;
}
</style>
